#include "hexparser.h"
#include "qdebug.h"
#include <QFile>

using namespace std;

HexParser::HexParser()
{

}

bool HexParser::ParseHex(QString filePath, uint32_t *Addr, uint32_t *Size, uint8_t *pData)
{
    QFile sourceFile(filePath);

    if (!sourceFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug()<<"文件打开失败！！"<<filePath;
    }

    QTextStream inStream(&sourceFile);

    if(!inStream.atEnd())
    {
        QString firstLine = inStream.readLine();

        if(firstLine[0] != ':')
        {
            *Addr = 0xFFFFFFFF;
            *Size = 0xFFFFFFFF;
            sourceFile.close();
            return false;
        }

        dataBytes = firstLine.mid(1, 2).toUShort(nullptr,16);
        recordType = firstLine.mid(7, 2).toUShort(nullptr,16);
        firtAddrs = firstLine.mid(9, 4).toUShort(nullptr,16);
        if(recordType == 0x02)
        {
            firtAddrs = firtAddrs << 4;
        }
        else if(recordType == 0x04)
        {
            firtAddrs = firtAddrs << 16;
        }

        QString secondLine = inStream.readLine();

        dataBytes = secondLine.mid(1, 2).toUShort(nullptr,16);
        recordType = secondLine.mid(7, 2).toUShort(nullptr,16);
        currAddrs = secondLine.mid(3, 4).toUShort(nullptr,16);

        *Addr = firtAddrs + currAddrs;
        *Size = 0;

        if(recordType == 0x00)
        {
            for(uint8_t idx = 0; idx < dataBytes; idx++)
            {
                pData[*Size + idx] = secondLine.mid(9 + idx * 2, 2).toUShort(nullptr,16);
            }
            *Size += dataBytes;
        }
    }

    while(!inStream.atEnd())
    {
        QString line = inStream.readLine();

        if(line[0] != ':')
        {
            *Addr = 0xFFFFFFFF;
            *Size = 0xFFFFFFFF;
            sourceFile.close();
            return false;
        }

        dataBytes = line.mid(1, 2).toUShort(nullptr,16);
        recordType = line.mid(7, 2).toUShort(nullptr,16);
        currAddrs = line.mid(3, 4).toUShort(nullptr,16);

        if(recordType == 0x00)
        {
            for(uint8_t idx = 0; idx < dataBytes; idx++)
            {
                pData[*Size + idx] = line.mid(9 + idx * 2, 2).toUShort(nullptr,16);
            }
            *Size += dataBytes;
        }
        else if(recordType == 0x01)
        {
            break;
        }
    }
    sourceFile.close();

    return true;
}
